import fs from '@ohos.file.fs';
import { pasteboard } from '@kit.BasicServicesKit';

export class FileUtil {
  /**
   * 读取文件流
   */
  static async readFileStream(filePath: string): Promise<ArrayBuffer> {
    let file: fs.File | null = null;
    try {
      // 打开文件
      file = await fs.open(filePath, fs.OpenMode.READ_ONLY);

      // 获取文件大小
      const stat = await fs.stat(file.path);
      const totalSize = stat.size;

      // 创建缓冲区
      const buffer = new ArrayBuffer(totalSize);
      const uint8Array = new Uint8Array(buffer);

      // 分块读取
      const CHUNK_SIZE = 64 * 1024; // 64KB
      let offset = 0;

      while (offset < totalSize) {
        const chunkSize = Math.min(CHUNK_SIZE, totalSize - offset);
        const chunk = new ArrayBuffer(chunkSize);

        const bytesRead = await fs.read(file.fd, chunk, {
          offset: offset,
          length: chunkSize
        });

        if (bytesRead === 0) {
          break;
        } // EOF

        // 复制数据到主缓冲区
        uint8Array.set(new Uint8Array(chunk), offset);
        offset += bytesRead;
      }

      return buffer;
    } catch (error) {
      throw new Error('Failed to read file stream: ' + error.message);
    } finally {
      // 确保关闭文件
      if (file !== null) {
        try {
          await fs.close(file);
        } catch (error) {
          console.error('Failed to close file:', error);
        }
      }
    }
  }

  /**
   * 获取文件大小
   */
  static async getFileSize(path: string): Promise<number> {
    try {
      const fileInfo = await fs.stat(path);
      return fileInfo.size;
    } catch (error) {
      console.error('Get file size failed:', error);
      throw error;
    }
  }

  /**
   * 获取文件类型
   */
  static getMimeType(fileName: string): string {
    const ext = fileName.split('.').pop()?.toLowerCase();
    const mimeTypes = {
      'jpg': 'image/jpeg',
      'jpeg': 'image/jpeg',
      'png': 'image/png',
      'gif': 'image/gif',
      'webp': 'image/webp',
      'mp4': 'video/mp4',
      'mp3': 'audio/mpeg',
      // 添加更多类型
    };
    return mimeTypes[ext] || 'application/octet-stream';
  }

  /**
   * 分片读取文件流
   */
  static async * createReadStream(filePath: string, chunkSize: number = 1024 * 1024): AsyncGenerator<ArrayBuffer> {
    let file: fs.File | null = null;
    try {
      // 打开文件
      file = await fs.open(filePath, fs.OpenMode.READ_ONLY);
      let position = 0;

      // 获取文件大小
      const stat = await fs.stat(filePath);
      const fileSize = stat.size;

      while (position < fileSize) {
        const buffer = new ArrayBuffer(Math.min(chunkSize, fileSize - position));
        const bytesRead = await fs.read(file.fd, buffer);

        if (bytesRead <= 0) {
          break;
        }

        position += bytesRead;
        yield buffer;
      }

      // 关闭文件
      await fs.close(file);

    } catch (error) {
      console.error('Read file stream failed:', error);
      throw error;
    }
  }


  static isUriPath(path: string): boolean {
    // 匹配 xxxx:// 格式的URI路径
    const regex = /^[a-z]+:\/\/.+/i;
    return regex.test(path);
  }

  // 或者指定特定的协议类型
  static isSpecificUriPath(path: string): boolean {
    // 匹配特定协议的URI路径
    const regex = /^(file|internal|dataability|content):\/\/.+/i;
    return regex.test(path);
  }

  /**
   * copy
   * @param text
   */
  public static copyText(text: string) {
    let pasteData: pasteboard.PasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
    pasteboard.getSystemPasteboard().setData(pasteData);
  }
}

